package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.SubjectExcelData;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SubjectDataListener extends AnalysisEventListener<SubjectExcelData> {

    // 通过构造器获取 subjectMapper
    SubjectMapper subjectMapper;
    public SubjectDataListener(SubjectMapper subjectMapper) {
        this.subjectMapper = subjectMapper;
    }

    // 每解析一行数据回调一次方法
    @Override
    public void invoke(SubjectExcelData subjectExcelData, AnalysisContext analysisContext) {

        // 获取一级分类和二级分类
        String levelOneTitle = subjectExcelData.getLevelOneTitle();
        String levelTwoTitle = subjectExcelData.getLevelTwoTitle();

        // 向数据库中保存一级标题, 根据title和parent_id = 0, 判断一级标题是否存在

        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getTitle, levelOneTitle);
        queryWrapper.eq(Subject::getParentId, 0);

        Subject levelOneSubject = subjectMapper.selectOne(queryWrapper);

        if (levelOneSubject == null) {
            // 向数据库中保存数据
            levelOneSubject = new Subject();
            levelOneSubject.setTitle(levelOneTitle);
            levelOneSubject.setParentId("0");
            levelOneSubject.setSort(0);
            subjectMapper.insert(levelOneSubject);
        }

        // 向数据库中保存二级标题, 判断title和 一级标题的id和二级标题的parent_id是否有相等的
        queryWrapper.clear(); // 清除queryWrapper 中的数据后, 可以复用
        queryWrapper.eq(Subject::getTitle, levelTwoTitle);
        queryWrapper.eq(Subject::getParentId, levelOneSubject.getId());

        Integer count = subjectMapper.selectCount(queryWrapper);
        if (count == 0) {
            Subject levelTwoSubject = new Subject();
            levelTwoSubject.setTitle(levelTwoTitle);
            levelTwoSubject.setParentId(levelOneSubject.getId());
            levelTwoSubject.setSort(0);

            subjectMapper.insert(levelTwoSubject);
        }

    }

    // 上传成功后的方法
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("subject数据解析完毕");
    }
}
